package com.bwie.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.poi.StringUtils;
import com.bwie.pojo.TbMenu;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbMenuService;
import com.bwie.service.TbUserService;
import com.bwie.utils.R;
import com.bwie.utils.Result;
import com.bwie.vo.LoginVo;
import com.bwie.vo.PageUserVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user/index")
@Slf4j
public class IndexController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    TbUserService tbUserService;

    @Autowired
    TbMenuService tbMenuService;


    /**
     * @description 登录接口
     * @params []
     * @return com.bwie.utils.R
     * @author 杰
     * @date 2025/5/21 16:42
     */
    @PostMapping("/login")
    public Result login(@RequestBody @Validated LoginVo loginVo){

        //判断登录用户是否存在
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();

        wrapper.lambda().eq(TbUser::getUserName,loginVo.getUserName());
        TbUser tbUser = tbUserService.getOne(wrapper);

        if (tbUser==null){
            return Result.error().setMsg("该账号不存在");
        }

        //加密
        String hex = DigestUtil.md5Hex(loginVo.getUserPass());
        log.info("加密后的密码为:"+hex);
        //判断密码是否正确
        if (!hex.equals(tbUser.getUserPass())){
            return Result.error().setMsg("密码错误");
        }


        String rediskey="token-"+tbUser.getUserId();

        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .claim("userName", tbUser.getUserName())
                .claim("nickName", tbUser.getNickName())
                .compact();


        redisTemplate.opsForValue().set(rediskey,token,15, TimeUnit.MINUTES);

        tbUser.setToken(token);
        tbUser.setUserPass(null);
        return Result.ok().setData(tbUser);
    }


    /**
     * @description 动态树形菜单
     * @params [request]
     * @return com.bwie.utils.Result
     * @author 杰
     * @date 2025/5/22 19:05
     */
    @PostMapping("/getMenuList")
    public Result getMenuList(HttpServletRequest request){

        String token = request.getHeader("token");

        if (token==null){
            return Result.error().setMsg("请先登录");
        }

        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);

      List<TbMenu> list= tbMenuService.getMenuList(userId);


      return Result.ok().setData(list);
    }


    @PostMapping("/getUserList")
    public Result getUserList(@RequestBody PageUserVo pageUserVo){

        Page<TbUser> page = new Page<>(pageUserVo.getPageNum(),pageUserVo.getPageSize());

        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(pageUserVo.getKeyWord())){
            wrapper.lambda().or().like(TbUser::getUserName,pageUserVo.getKeyWord());
            wrapper.lambda().or().like(TbUser::getNickName,pageUserVo.getKeyWord());
            wrapper.lambda().or().like(TbUser::getUserMobile,pageUserVo.getKeyWord());
            wrapper.lambda().or().like(TbUser::getUserEmail,pageUserVo.getKeyWord());
        }
        if (pageUserVo.getGender()!=null){
            wrapper.lambda().eq(TbUser::getGender,pageUserVo.getGender());
        }
        if (StringUtils.isNotEmpty(pageUserVo.getStartTime())){
            wrapper.lambda().ge(TbUser::getCreateTime,pageUserVo.getStartTime());
        }
        if (StringUtils.isNotEmpty(pageUserVo.getEndTime())){
            wrapper.lambda().le(TbUser::getCreateTime,pageUserVo.getEndTime());
        }




        Page<TbUser> tbUserPage = tbUserService.page(page, wrapper);

        return Result.ok().setData(tbUserPage);

    }



    /**
     * @description 修改商户
     * @params []
     * @return com.bwie.utils.Result
     * @author 杰
     * @date 2025/5/22 20:20
     */
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody TbUser tbUser){

        return tbUserService.updateUser(tbUser);
        
    }

    /**
     * @description 上传图片
     * @params [file]
     * @return com.bwie.utils.Result
     * @author 杰
     * @date 2025/5/23 9:15
     */

    @PostMapping("/uploade")
    public Result uploade(@RequestPart("file")MultipartFile file){

        return tbUserService.uploade(file);
    }


    /**
     * @description 单删
     * @params [userId]
     * @return com.bwie.utils.Result
     * @author 杰
     * @date 2025/5/23 9:33
     */
    @PostMapping("/deleteUser/{userId}")
    public Result deleteUser(@PathVariable(name = "userId") Integer userId){

        return tbUserService.deleteUser(userId);
    }


    /**
     * @description 批量删除
     * @params [tbUsers]
     * @return com.bwie.utils.Result
     * @author 杰
     * @date 2025/5/23 9:44
     */
    @PostMapping("/DeleteAllByUser")
    public Result DeleteAllByUser(@RequestBody List<TbUser> tbUsers){

        return tbUserService.DeleteAllByUser(tbUsers);
    }


    /**
     * @description 审核商户
     * @params [tbUser]
     * @return com.bwie.utils.Result
     * @author 杰
     * @date 2025/5/23 15:38
     */
    @PostMapping("/checkUser")
    public Result checkUser(@RequestBody TbUser tbUser){
        return tbUserService.checkUser(tbUser);
    }

}
